// pages/charge/charge.js
const app = getApp();
import * as echarts from '../../ec-canvas/echarts';
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');
//图表对象
let Chart2=null;
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
//去掉尾部的0
const regexp=/(?:\.0*|(\.\d+?)0+)$/;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //传参来的imei
    imei:null,
    //图表
    ec2: {
      lazyLoad: true
    },
    //是否显示图表（避免遮挡）
    showChart:true,
    showChart2:true,
    //无数据
    showNoData2:false,
    chartSet2:{
      barColor:'#6BD5FF',
      title:'（次）'
    },
    //今日日期
    todayDate:util.timeFormatDay(new Date()),
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:'',
    //选择周
    showWeek:false,
    //周的选择列表
    weekList:[],
    //显示的周
    weekWord:'本周',
    //选中的周
    selectedWeek:{
      start:'',
      end:''
    },
    //日统计到几天前
    dayNum:7,
    //周统计到几周前
    weekNum:7,
    //查询的设备
    equipment:{},

    //明细列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取传参过来的设备信息
    this.setData({
			imei: options.imei
    })
    //计算本周和上几周的日期
    this.getWeekList();
    //周统计数据
    this.getWeekData();
  },

  //周统计数据
  getWeekData(){
    this.setData({
      showNoData2:false,
      showChart2:true
    })

    //图表组件
    this.echartsComponnet2 = this.selectComponent('#mychart2');

    //清空数据
    let chartData={
      xData:[],
      yData:[]
    }

    let parameter={
      "className": "com.jbn.model.iot.IotChargingModeRecord",
      "condition": [{
        "fieldName": "imei",
        "relation": "=",
        "value": this.data.imei
      }, {
        "fieldName": "startTime",
        "dataType": "date",
        "relation": ">=",
        "value": this.data.selectedWeek.start+' 00:00:00'
      }, {
        "fieldName": "startTime",
        "dataType": "date",
        "relation": "<=",
        "value": this.data.selectedWeek.end+' 23:59:59'
      }],
      "checkDataAuthority": false,
      "sortField": "_id",
      "sortDirection": "asc",
      "statisticsModel": {
        "operate": "count",
        "groupField": "startTime",
        "groupFieldType": "date",
        "staField": "intervals",
        "staType": "Long",
        "groupDateType": "day",
        "projectField": ["intervals", "startTime", "imei"]
      }
    }
    CommonService.findList(parameter).then(res=>{
      if(res.data.data){
        let result=res.data.data;
        console.log('充电数据');
        console.log(result);
        if(result.length){
          result.forEach(item => {
            //日期转化为周
            let day=new Date(item._id.replaceAll("-","/"));
            chartData.xData.push(util.timeFormatWeek(day));

            //图表数据中加入日期，用于点击事件的传参
            let yObj={
              date:util.timeFormatDay(day),
              value:item.staResult
            }
            chartData.yData.push(yObj);
          });

          this.setData({
            showNoData2:false,
            showChart2:true
          })

          //判断图表是否第一次绘制
          this.isHaveChart(Chart2,this.echartsComponnet2,this.data.chartSet2,chartData);

        }else{
          this.setData({
            showNoData2:true,
            showChart2:false,
            currentDateStr:'',
            list:[]
          })
        }
      }else{
        this.setData({
          showNoData2:true,
          showChart2:false,
          currentDateStr:'',
          list:[]
        })
      }
    })
  },

  //判断图表是否第一次绘制
  isHaveChart(chartObj,componnetObj,setObj,dataObj){
    if (!chartObj){
      //如果是第一次绘制，则初始化图表
      this.init_echarts(chartObj,componnetObj,setObj,dataObj);
    }else{
      //更新图表数据
      this.setOption(chartObj,setObj,dataObj);
    }
  },

  //初始化图表
  init_echarts: function (chartObj,componnetObj,setObj,dataObj) {
    componnetObj.init((canvas, width, height) => {
      chartObj = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      this.setOption(chartObj,setObj,dataObj);
      return chartObj;
    });
  },

  //更新图表数据
  setOption: function (chartObj,setObj,dataObj) {
    //清除
    chartObj.clear();
    //设置新数据
    chartObj.setOption(this.getOption(chartObj,setObj,dataObj));
  },

  //指定图表的配置项和数据
  getOption: function (chartObj,setObj,dataObj) {
    //文字颜色
    let fontColor='#666';

    let option = {
      grid: {
        left: '5%',
        right: '2%',
        top: '20%',
        bottom: '5%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          color: fontColor,
          fontSize : 13,
          interval:0
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        data: dataObj.xData,
      },
      yAxis: {
        type: 'value',
        name: setObj.title,
        axisLabel: {
          show:false,
          color: fontColor,
          fontSize : 14,
        },
        axisLine: {
          lineStyle: {
            color: setObj.barColor
          }
        },
        splitLine: {
          lineStyle: {
            color: '#eee'
          }
        },
        minInterval: 1
      },
      series: [{
        barWidth : '15px',
        data: dataObj.yData,
        type: 'bar',
        label:{
          normal:{
            fontSize:14,
            rich:{}
          }
        },
        itemStyle:{
          normal:{
              label:{
                  show:true,
                  position:'top',
                  color:fontColor,
                  formatter: function(params) {
                    return params.value;
                  },
              },
              color: setObj.barColor
          }
      },
      }]
    };

    let _this=this;

    //首先移除事件，不然会造成多次点击
    chartObj.off('click');
    //点击柱状图
    chartObj.on('click', function (params) {
      _this.setData({
        currentDateStr: params.data.date
      })
      //获取明细数据
      _this.refreshListAndPage();

    })

    return option;
  },

  //隐藏图表
  hideChart(){
    this.setData({
      showChart:false
		})
  },

  //显示图表
  showChart(){
    this.setData({
      showChart:true
		})
  },

  //计算本周和上几周的日期
  getWeekList(){
    //当前日期
    let today=new Date();
    let day = today.getDay() || 7;
    //本周周一
    let monday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1 - day);
    //本周周日
    let sunday=new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7 - day);

    //周统计初始参数赋值
    this.setData({
      selectedWeek:{
        start:util.timeFormatDay(monday),
        end:util.timeFormatDay(today)
      }
		})

    //本周
    let weekList=[{
      text:util.timeFormatDay(monday) +' 至 '+ util.timeFormatDay(today),
      start:util.timeFormatDay(monday),
      end:util.timeFormatDay(today),
      word:util.timeFormatDay(monday).slice(5) +' 至 '+ util.timeFormatDay(today).slice(5)
    }];

    let n=this.data.weekNum;
    for(let i=1;i<=n;i++){
      let lastMonday=util.countPrevDay(monday,7);
      let lastSunday=util.countPrevDay(sunday,7);
      let obj={
        text:util.timeFormatDay(lastMonday) +' 至 '+ util.timeFormatDay(lastSunday),
        start:util.timeFormatDay(lastMonday),
        end:util.timeFormatDay(lastSunday),
        word:util.timeFormatDay(lastMonday).slice(5) +' 至 '+ util.timeFormatDay(lastSunday).slice(5)
      }
      weekList.push(obj);
    }

    this.setData({
      weekList: weekList
		})
  },

  //显示选择周的日期
  onShowWeekSelect(){
    this.setData({
			showWeek: true
    })
    //隐藏图表
    this.hideChart();
  },

  //隐藏选择周的日期
  onCloseWeek(){
    this.setData({
			showWeek: false
    })
    //显示图表
    this.showChart();
  },

  //确认选择周的日期
  onConfirmWeek(e){
    let obj=e.detail.value;
    this.setData({
      weekWord: obj.word,
      selectedWeek:obj
    })
    //隐藏选择周的日期
    this.onCloseWeek();
    //请求周统计数据
    this.getWeekData();
  },

  //获取明细数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param={
      source:"小程序，充电记录，查询某一天的充电明细",
      className:"com.jbn.model.iot.IotChargingModeRecord",
      checkDataAuthority:false,
      "condition": [{
          "fieldName": "imei",
          "relation": "=",
          "value": this.data.imei
        },{
          "fieldName": "startTime",
          "dataType": "date",
          "relation": ">=",
          "value": this.data.currentDateStr+' 00:00:00'
        }, {
          "fieldName": "startTime",
          "dataType": "date",
          "relation": "<=",
          "value": this.data.currentDateStr+' 23:59:59'
        }],
      sortField: "startTime",
      page:{
        page:this.data.page,
        rows:10
      },
    }

    CommonService.findList(param).then(res=>{
      Toast.clear();

      if(res.data.data){
        let result=res.data.data.result;
        console.log('充电明细');
        console.log(result);

        if(result.length){
          result.forEach(item => {
            if (item.intervals){
              item.long=(item.intervals/1000/60/60).toFixed(1).replace(regexp,'$1');
            }
          });

          this.setData({
            list: this.data.list.concat(result)
          });
        }else{
          this.setData({
            notMore: false
          })
          if(this.data.page==1){
            this.setData({
              showNothing: true
            });
          }else{
            Toast.fail('没有更多了');
          }
        }
      }else{
        this.setData({
          showNothing: true
        });
      }
    }).catch((error) => {
      Toast.clear();
      this.setData({
        showNothing: true
      });
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
